<template>
  <div class="upload-file">
    <el-button type="primary" :disabled="disabled" @click="openUpload">选取文件</el-button>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in newFileList" :key="index">
        <el-link @click="handleDownload(file)" :underline="false" target="_blank">
          <span class="el-icon-document">&nbsp;&nbsp;{{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index, file)" type="danger" :disabled="disabled">删除</el-link>
        </div>
      </li>
    </transition-group>
    <!-- 上传对话框 -->
    <el-dialog v-if="upload.open" :title="upload.title" v-model="upload.open" width="400px" append-to-body
      custom-class="dialogTable">
      <p></p>
      <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload"
        :limit="limits" :on-change="handleChange" :on-error="handleUploadError"  :on-remove="handleRemove" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :show-file-list="true" :headers="upload.headers"
        class="upload-file-uploader" ref="uploads" :auto-upload="true" style="display: inline-block"
        :disabled="disabled" :fileType="fileType" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <!-- 上传提示 -->
          <div class="el-upload__tip text-center">
            <template v-if="showTip">
              请上传
              <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
              <template v-if="fileType.length != 0"> 格式为 <b style="color: #f56c6c">{{ fileType.join(",") }}</b>
              </template>
              的文件
            </template>
            <!--<template v-if="showTip&&isSpatialData!='0'">
              导入多个文件时，文件名称需相同。支持上传多个文件。
            </template>-->
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                @click="importTemplate()">下载模板</el-link>
            <template v-if="name">
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                @click="importTemplate(name)" v-if="isSpatialData == '0'">下载模板</el-link>
            </template>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="(fileList.length == 0)||(isSpatialData=='1'&&uploadDisabled)" @click="submitFileForm">确 定</el-button>
          <el-button @click="(upload.open = false)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传图片 -->
    <el-drawer v-model="openDrawer" direction="btt" append-to-body size="40%"
      :close-on-click-modal="false" :show-close="false">
      <template #title>
        <h4>{{ title }}</h4>
        <el-button type="primary" @click="cancelDrawer">关 闭</el-button>
      </template>
      <template #default>
        <el-table v-loading="loading" ref="tableRefs" :data="dataList" stripe>
          <template v-for="item in titleList">
            <el-table-column :label="item.label" align="center" :prop="item.prop" />
          </template>
          <el-table-column label="操作" fixed="right" align="center" width="200" class-name="small-padding fixed-width">
            <template #default="scope">
              <template v-if="show == '0'">
                <el-button type="text" v-if="scope.row.excel != 2"
                  @click="handleUplodeReport(scope.row)">编辑报告</el-button>
                <el-button type="text" v-else @click="handleUplodeReport(scope.row)">上传报告</el-button>
              </template>
              <template v-if="show == '1'">
                <el-button type="text" v-if="scope.row.picture == 2"
                  @click="handleUplodePic(scope.row)">编辑图片</el-button>
                <el-button type="text" v-else @click="handleUplodePic(scope.row)">上传图片</el-button>
              </template>
              <template v-if="show == '2'">
                <el-button type="text" v-if="scope.row.picture == 2"
                  @click="handleUplodePic(scope.row)">编辑图片</el-button>
                <el-button type="text" v-else @click="handleUplodePic(scope.row)">上传图片</el-button>
                <el-button type="text" v-if="scope.row.excel == 2"
                  @click="handleUplodeReport(scope.row)">编辑报告</el-button>
                <el-button type="text" v-else @click="handleUplodeReport(scope.row)">上传报告</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-drawer>

    <el-dialog v-model="openPic" width="500px" title="上传图片" append-to-body>
      <p class="mt15"></p>
      <div>
        <image-upload ref="imageUploadRef" :limit="5" v-model="form.attach" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="savePic">确定</el-button>
          <el-button type="primary" @click="openPic = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上传对话框 -->
    <el-dialog v-if="openRep" :title="上传报告" v-model="openRep" width="400px" append-to-body custom-class="dialogTable">
      <p></p>
      <upload-report v-model="form.reportAttach" ref="reportRef" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveRep">确 定</el-button>
          <el-button type="primary" @click="(openRep = false)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { ElMessageBox } from 'element-plus'
import { getListExcel,getListsShp, uploadSave, getFileData } from '@/api/essentialData/dataView'
import { upLoadFile, downLoadFile, deleteFile } from "@/api/system/attachFile";
import uploadReport from '../fileUploadReport/index.vue'

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 100,
  },
  // 是否是空间数据
  isSpatialData: {
    type: Number,
    default: 2,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    //default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    default: () => [],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  code: {
    type: String,
    default: '',
  },
  name: {
    type: String,
    default: '',
  },
  isHasFile: {
    type: Number,
    default: 0,
  }
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const fileList = ref([]);
const openDrawer = ref(false);
const loading = ref(false);
const dataList = ref([]);
const titleList = ref([]);
const title = ref('');
const show = ref('0');
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const limits = computed(
  () =>{
    props.isSpatialData == 0 ? 1 : 10
  }
);
const newFileList = ref([]);
const dataVersion = ref();

const openPic = ref(false);
const openRep = ref(false);
const uploadDisabled = ref(true);
const id = ref('');
/*** 用户导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "tokrn " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile", // 上传的图片服务器地址
});
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile"); // 上传的图片服务器地址

const data = reactive({
  form: {
    attach: [],
    reportAttach: [],
  },
})
const { form } = toRefs(data);
watch(() => props.modelValue, val => {
  // debugger
  if (val) {

    let temp = 1;
    // 首先将值转为数组
    const list = Array.isArray(val) ? val : props.modelValue.split(',');
    // 然后将数组转为对象数组
    newFileList.value = list.map(item => {
      if (typeof item === "string") {
        item = { name: item, url: item };
      }
      item.attachId = item.attachId || new Date().getTime() + temp++;
      item.name = item.attachName;
      item.url = item.attachPath;
      return item;
    });
  } else {
    newFileList.value = [];
    return [];
  }
}, { deep: true, immediate: true });

// 上传报告
function handleUplodeReport (row) {
  id.value = row.id;
  getFileData({ id: row.id, typeCode: props.code, show: '0' }).then(res => {
    form.value.reportAttach = res.data ? res.data : [];
    openRep.value = true;
  })
}

// 保存报告
function saveRep () {
  const fileList = JSON.parse(JSON.stringify(proxy.$refs["reportRef"].fileList));
  const attachIds = [];
  for (var i = 0; i < fileList.length; i++) {
    attachIds.push(fileList[i].attachId)
  }
  const ids = attachIds.join(",");
  uploadSave({ ids: ids, id: id.value, typeCode: props.code, show: '0' }).then(res => {
    proxy.$modal.msgSuccess("保存成功");
    openRep.value = false;
  })
}
// 上传图片
function handleUplodePic (row) {
  id.value = row.id;
  getFileData({ id: row.id, typeCode: props.code, show: '1' }).then(res => {
    form.value.attach = res.data ? res.data : [];
    openPic.value = true;
  })
}

// 保存图片
function savePic () {
  const fileList = JSON.parse(JSON.stringify(proxy.$refs["imageUploadRef"].fileList));
  const attachIds = [];
  for (var i = 0; i < fileList.length; i++) {
    attachIds.push(fileList[i].attachId)
  }
  const ids = attachIds.join(",");
  uploadSave({ ids: ids, id: id.value, typeCode: props.code, show: '1' }).then(res => {
    proxy.$modal.msgSuccess("保存成功");
    openPic.value = false;
  })
}

// 关闭
function cancelDrawer () {
  openDrawer.value = false;
  newFileList.value = fileList.value;
  emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value });

}

// 打开图片上传
function submitFileForm () {
  if(props.isSpatialData=='1'){//空间数据
    let nameArr = [];
    fileList.value.forEach(item=>{
      const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
      nameArr.push(typeName)
    })
    if((nameArr.includes('shp'&&'dbf'&&'prj'&&'shx'&&'cpg'))&&props.isSpatialData=='1'){
      newFileList.value = [];
      let id = [];
      fileList.value.forEach(item => {
        id.push(item.attachId)
      })
      proxy.$modal.loading("正在解析文件，请稍候...");
      getListsShp({ typeCode: props.code, fileIds: id.join(',') }).then(res => {
        proxy.$modal.closeLoading();
        dataList.value = res.data.list;
        titleList.value = res.data.name;
        title.value = res.data.typeName;
        dataVersion.value = res.data.dataVersion;
        show.value = res.data.show;
        if (res.data.open == '1') {
          openDrawer.value = true;
          upload.open = false;
        } else {
          newFileList.value = fileList.value;
          emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value });
          upload.open = false;
        }
      }).catch(err => {
        proxy.$modal.closeLoading();
      });
    }else{
      proxy.$modal.msgError(`.dbf、.prj、.shp、.shx、.cpg类型的文件必须上传！ `);
    }
  }else{
    newFileList.value = [];
    let id = [];
    fileList.value.forEach(item => {
      id.push(item.attachId)
    })
    proxy.$modal.loading("正在解析文件，请稍候...");
    getListExcel({ versionCode: props.code, fileIds: id.join(',') }).then(res => {
      proxy.$modal.closeLoading();
      newFileList.value = fileList.value;
      emit('sureUploadFile', { list: newFileList.value});
      upload.open = false;
//    dataList.value = res.data.list;
//    titleList.value = res.data.name;
//    title.value = res.data.typeName;
//    dataVersion.value = res.data.dataVersion;
//    show.value = res.data.show;
//    if (res.data.open == '1') {
//      openDrawer.value = true;
//      upload.open = false;
//    } else {
//      newFileList.value = fileList.value;
//      emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value });
//      upload.open = false;
//    }
    }).catch(err => {
      proxy.$modal.closeLoading();
    });
  }



};

//// 模板下载
//function importTemplate (name) {
//proxy.download("/fxfzaqbz/data/downloadExcel", {
//  fileName: name
//}, name);
//};

// 模板下载
function importTemplate () {
  proxy.download("/landslideSite/downloadExcel", {
    fileName: '滑坡现场调查数据导入模板.xls'
	}, '滑坡现场调查数据导入模板.xls');
};

function openUpload () {
//if (!props.code) {
//  ElMessageBox.alert('请先选择子数据类别', '消息提示', {
//    confirmButtonText: '确认',
//    type: 'warning'
//  })
//} else {
    uploadDisabled.value = true;
    fileList.value = [];
    upload.title = "上传";
    upload.open = true;
//}
}

// 上传前校检格式和大小
function handleBeforeUpload (file) {
  // 校检文件类型
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    const isTypeOk = props.fileType.some((type) => {
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }

  if(!props.fileType.length){
     // 非第一次上传
     console.log(fileList.value,'校验数组');
    if(fileList.value.length){
   var falg =   fileList.value.some(item=>{
        const name = item.name.slice(0,item.name.lastIndexOf("."));
        const fileName = file.name.slice(0,file.name.lastIndexOf("."));
        console.log(name,fileName,'名称对比');
        if(name!=fileName){
          const uploadName = fileList.value[0].name.slice(0,fileList.value[0].name.lastIndexOf("."));
          proxy.$modal.msgError(`文件名称不正确, 请上传名称为${uploadName}的文件!`);
          return true;
        }
      })
      if(falg){ return false;}
      var falg1 =   fileList.value.some(item=>{
        const typeName  = item.name.slice(item.name.lastIndexOf(".") + 1);
        const typeFileName = file.name.slice(file.name.lastIndexOf(".") + 1)
        if((typeName=='shp'&&typeFileName==typeName)||(typeName=='dbf'&&typeFileName==typeName)||(typeName=='prj'&&typeFileName==typeName)||(typeName=='shx'&&typeFileName==typeName)||(typeName=='cpg'&&typeFileName==typeName)){
          proxy.$modal.msgError(`该类型文件只能上传一个!`);
          return true;
        }
      })
      if(falg1){return false;}
  }
  }
  
  // 校检文件大小
  if (props.fileSize) {
    if(props.isSpatialData=='1'){
      var isLt = file.size / 1024 / 1024 < 500;
      if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过500MB!`);
      return false;
    }
    }else{
      var isLt1 = file.size / 1024 / 1024 < props.fileSize;
      if (!isLt1) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  upload.isUploading = true;
  number.value++;
  return true;
}

function handleChange (file, fileList) {
  fileList.value = fileList;
}

// 文件个数超出
function handleExceed () {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError (err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess (res, file) {
  if (res.code == 200) {
    fileList.value.push({ attachId: res.data[0].attachId, name: res.data[0].attachName, url: res.data[0].attachPath });
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("上传文件成功");
    emit('uploadFile', fileList.value);
    let nameArr = [];
  fileList.value.forEach(item=>{
    const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
    nameArr.push(typeName)
  })
  console.log(nameArr,'校验数据');
  console.log(nameArr.includes('shp'&&'dbf'&&'prj'&&'shx'&&'cpg'),'包含');
  if((nameArr.includes('shp'&&'dbf'&&'prj'&&'shx'&&'cpg'))&&props.isSpatialData=='1'){
    console.log('1111111');
    console.log('上传文件可以解析');
    uploadDisabled.value = false;
}else{
  console.log('2222222222');
  uploadDisabled.value = true;
}
  }
}

// 删除文件
function handleDelete (index, file) {
  // fileList.value.splice(index, 1);
  // emit('delFile', fileList.value);
  newFileList.value = [];
  emit('dels',[])
}

// 删除文件
function handleRemove (file, uploadFiles) {
  console.log(file.response.data[0].attachId);
  const index = fileList.value.findIndex(item => item.attachId === file.response.data[0].attachId)
  fileList.value.splice(index, 1)
}


// 下载文件
function handleDownload (file) {
  var query = {
    attachId: file.attachId,
    name: file.attachName
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

function getFileName (name) {
  return name
}

defineExpose({
  fileList
});
</script>

<style scoped lang="scss">
.upload-file {
  width: 100%;
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.el-upload-list__item-name{
  width: 310px!important;
  // white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
